package com.x.provider.customer.service.customer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.x.provider.api.customer.model.dto.customer.CustomerVerificationSaveReqDTO;
import com.x.provider.customer.mapper.CustomerVerificationMapper;
import com.x.provider.customer.model.domain.customer.CustomerVerification;
import com.x.provider.customer.model.query.customer.CustomerVerificationQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class CustomerVerificationServiceImpl implements CustomerVerificationService{

    private final CustomerVerificationMapper customerVerificationMapper;

    public CustomerVerificationServiceImpl(CustomerVerificationMapper customerVerificationMapper){
        this.customerVerificationMapper = customerVerificationMapper;
    }

    @Override
    public List<CustomerVerification> list(CustomerVerificationQuery query){
        return customerVerificationMapper.selectList(build(query));
    }

    @Override
    public CustomerVerification get(CustomerVerificationQuery customerVerificationQuery){
        return customerVerificationMapper.selectOne(build(customerVerificationQuery));
    }

    private LambdaQueryWrapper<CustomerVerification> build(CustomerVerificationQuery query){
        LambdaQueryWrapper<CustomerVerification> queryWrapper = new LambdaQueryWrapper<>();
        if (query.getCustomerId() != null){
            queryWrapper.eq(CustomerVerification::getCustomerId, query.getCustomerId());
        }
        if (!CollectionUtils.isEmpty(query.getCustomerIdList())){
            queryWrapper.in(CustomerVerification::getCustomerId, query.getCustomerIdList());
        }
        if (query.getVerificationType() != null){
            queryWrapper.eq(CustomerVerification::getVerificationType, query.getVerificationType());
        }
        return queryWrapper;
    }

    @Override
    public void save(CustomerVerificationSaveReqDTO req) {
        CustomerVerification entity = get(CustomerVerificationQuery.builder().customerId(req.getCustomerId()).verificationType(req.getVerificationType()).build());
        if (entity != null && entity.getPass().equals(req.getPass())){
            return;
        }
        if (entity == null){
            entity = new CustomerVerification();
        }
        BeanUtils.copyProperties(req, entity);
        if (entity.getId() == null) {
            customerVerificationMapper.insert(entity);
        }
        else{
            customerVerificationMapper.updateById(entity);
        }
    }
}
